<template>
    <div class="page-main GetCheck">
        <div class="table-search marb-5" style="padding-left: 5px;"> 
            <div style="display: flex; gap: 10px;">
                <div>
                    <div style="display: flex; align-items: center; gap: 5px;">
                        <el-text tag="b">边缘机地址</el-text>
                        <div>
                            <el-input v-model.trim="edgeIpAndPort" 
                                @blur="validateUrl"
                                @input="updateEdgeUrl"
                                :class="{ 'input-error': urlError }"
                                clearable />
                        </div>
                    </div>
                    <div>
                        <span v-if="urlError" style="color: #f56c6c; font-size: 12px;">{{ urlError }}</span>
                        <span v-else style="color: #909399; font-size: 12px;">格式: IP地址或域名 + 端口号 (如 192.168.1.1:8080)</span>
                    </div>
                </div>
                <div>
                    <div style="display: flex; align-items: center; gap: 5px;">
                        <el-text tag="b">设备ID</el-text>
                        <div>
                            <el-input v-model="deviceId" type="number" min="1"
                                @blur="validateDeviceId"
                                @input="validateDeviceId"
                                :class="{ 'input-error': deviceIdError }"
                                clearable />
                        </div>
                    </div>
                    <div>
                        <span v-if="deviceIdError" style="color: #f56c6c; font-size: 12px;">{{ deviceIdError }}</span>
                    </div>
                </div>
                <div>
                    <el-button @click="onQuery" type="primary">
                        <el-icon><Search /></el-icon>
                    </el-button>
                </div>
            </div>
        </div>
        <div>      
            <DataTable
                ref="StatusMonitorDataTableRef"
                :data="list"
                :hasTop="false"
                :hasAdd="false"
                :hasFilter="false"
                :hasCheckbox="false"
                :page-index="edgeReq.pageNum"
                :page-size="edgeReq.pageSize"
                :total-count="pageInfo.totalCount"
                divHeight="calc(100vh - 211px)"
                @page-change="onPageChange"
                v-bind="$attrs">
                <vxe-column title="钢丝绳类型" min-width="50" show-overflow>
                    <template #default="{ row }">
                        {{ row.header.rigType || "-" }}
                    </template>
                </vxe-column>

                <vxe-column title="钢丝绳编号" min-width="50" show-overflow>
                    <template #default="{ row }"> 
                        {{ row.header.rigSN || "-" }} </template>
                </vxe-column>

                <vxe-column title="钢丝绳直径" min-width="50" show-overflow>
                    <template #default="{ row }">
                        {{ row.header.diameter || "-" }}
                    </template>
                </vxe-column>

                <vxe-column title="公司" min-width="50" show-overflow>
                    <template #default="{ row }"> 
                        {{ row.header.company || "-" }} </template>
                </vxe-column>

                <vxe-column title="负责人" min-width="50" show-overflow>
                    <template #default="{ row }"> 
                        {{ row.header.responsiblePerson }} </template>
                </vxe-column>

                <vxe-column title="报告名" min-width="50" show-overflow>
                    <template #default="{ row }"> 
                        {{ row.reportName }} </template>
                </vxe-column>

                <vxe-column title="报告生成时间" min-width="100" show-overflow>
                    <template #default="{ row }">
                        {{ row.header.time ? new Date(row.header.time*1000).toLocaleString() : "-" }}                           </template>
                </vxe-column>

                <vxe-column title="状态" min-width="50" show-overflow>
                    <template #default="{ row }"> 
                        {{ row.result.state }} </template>
                </vxe-column>

                <vxe-column title="内容" min-width="200" show-overflow>
                    <template #default="{ row }"> 
                        {{ row.result.text || "-" }}m </template>
                </vxe-column>

            </DataTable>
        </div>  
    </div>
</template>

<script lang="ts" setup>
import { valueEquals } from "element-plus";
import { DatePart, HttpType } from "@/_gx/TsEnums";
import Enums from "@/gx/Enums";
import Gx from "@/gx/Gx";
import { Console } from "console";
/********************************************** 列表相关定义 **********************************************/

//表格的数据
const list = ref([]);

//分页信息
const pageInfo = reactive({
    pageIndex: 1,
    pageSize: 20,
    totalCount: 0,
});

const edgeIpAndPort = ref('192.168.0.113:4523');
const edgeUrl = ref('');
const deviceId = ref(123456);
const urlError = ref('');
const deviceIdError = ref('');

interface EdgeReq {
  pageNum: number;
  pageSize: number;
  deviceId: number;
  reportCreateTimeMin?: number;
  reportCreateTimeMax?: number;
  reportName?: string[];
}
const edgeReq = reactive<EdgeReq>({
  pageNum: 1,
  pageSize: 20,
  deviceId: deviceId.value
});

//搜索条件
const filterModel = ref<any>({});

//搜索条件空对象的json字符串，用于清空搜索条件时使用
const filterModelJson = Gx.SerializeObject(filterModel.value);

/********************************************** 列表方法与事件 **********************************************/

//页面加载
onMounted(() => {
    // Init();
});

//初始化
const Init = () => {
};


const validateUrl = () => {
    urlError.value = '';

    const input = edgeIpAndPort.value.trim();
    if (!input) {
        urlError.value = '请输入服务地址';
        return false;
    }

    const [host, port] = input.split(':');
    if (!port) {
        urlError.value = '必须包含端口号 (如 :8080)';
        return false;
    }

    const ipv4Pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    const domainPattern = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i;

    if (!ipv4Pattern.test(host) && !domainPattern.test(host) && host !== 'localhost') {
        urlError.value = '请输入有效的IP地址或域名';
        return false;
    }

    // 校验端口
    const portNum = parseInt(port);
    if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
        urlError.value = '端口号必须是1-65535之间的数字';
        return false;
    }

    return true;
};

const validateDeviceId = () => {
    if (!deviceId.value && deviceId.value !== 0) {
        deviceIdError.value = '请输入设备ID';
        return false;
    }

    if (isNaN(deviceId.value) || deviceId.value <= 0) {
        deviceIdError.value = '请输入有效的设备ID (正整数)';
        return false;
    }

    deviceIdError.value = '';
    return true;
};

const onQuery = (isSave: boolean = true) => {
    InsertMagnetHeadTblIfNotExist(isSave);
};

// public static readonly _API_URL: string = import.meta.env.VITE_API_URL as string;
// let baseUrl = Config._API_URL;
// let apiUrl = baseUrl + "/api";
const InsertMagnetHeadTblIfNotExist = (isSave: boolean = true) => {
    App.CallApi(Api.MagnetHead.Insert, {
        data: {
            DeviceID: deviceId.value
        },
        success: () => {
            GetLastCheckTime(isSave);
        },
        fail: () => {
            GetLastCheckTime(isSave);
        }
    });
}

const GetLastCheckTime = (isSave: boolean = true) => {
    App.CallApi(Api.MHCheck.GetLastCheckTime(deviceId.value), {
        success: (data) => {
            if (!data) {
                if ('reportCreateTimeMin' in edgeReq) {
                    delete edgeReq.reportCreateTimeMin;
                }
                if ('reportCreateTimeMax' in edgeReq) {
                    delete edgeReq.reportCreateTimeMax;
                }
            } else {
                edgeReq.reportCreateTimeMin = data + 1;
                edgeReq.reportCreateTimeMax = Math.floor(Date.now() / 1000);
            }
            edgeReq.deviceId = deviceId.value;
            GetReportsContent(isSave);
        }
    });
}

const GetReportsContent = (isSave: boolean = true) => {
    updateEdgeUrl();
    App.CallApi({
        url: edgeUrl.value,
        method: HttpType.POST,   
        data: edgeReq,
        success: (res: any) => {
            Insert2RptTbl(isSave, res);
        },
        fail: (res: any) => {
            Insert2RptTbl(isSave, res.data);
        },
        exception: (res: any) => {
            Insert2RptTbl(isSave, res.data);
        },
    });
}

const Insert2RptTbl = (isSave: boolean = true, res: any) => {
    list.value = res.reports;
    pageInfo.totalCount = res.totalReports;
    // res.reports.forEach((report:any, index:any) => {
    //   console.log(`\n报告 #${index + 1}`);
    //   console.log(`报告名称: ${report.reportName}`);
    //   console.log(`创建时间: ${new Date(report.createTime).toLocaleString()}`);
      
      // console.log('\n报告头信息:');
      // console.log(`时间: ${new Date(report.header.time*1000).toLocaleString()}`);
    //   console.log(`公司: ${report.header.company}`);
    //   console.log(`钻机类型: ${report.header.rigType}`);
    //   console.log(`钻机序列号: ${report.header.rigSN}`);
    //   console.log(`直径: ${report.header.diameter}`);
    //   console.log(`负责人: ${report.header.responsiblePerson}`);
      
    //   console.log('\n报告结果:');
    //   console.log(`状态: ${report.result.state}`);
    //   console.log(`文本内容: ${report.result.text}`);
    // });
    if (!isSave) {
        return;
    }
    let _data = res.reports.map((x) => {
        return {
            DeviceID: deviceId.value,
            WireropeType: x.header.rigType,
            WireropeSN: x.header.rigSN,
            Diameter: x.header.diameter,
            Company: x.header.company,
            ResponsiblePerson: x.header.responsiblePerson,
            ReportName: x.reportName,
            CheckTime: x.header.time,
            State: x.result.state,
            Content: x.result.text
        };
    });
    App.CallApi(Api.MHCheck.BatchInsert, {
        data: _data,
    });

    // if (res.pageNum * res.pageSize < res.totalReports) {
    //     edgeReq.pageNum = res.pageNum + 1;
    //     // 使用 setTimeout 避免栈溢出
    //     setTimeout(() => {
    //         GetReportsContent();
    //     }, 0);
    // }
}

//分页改变
const onPageChange = (data: any) => {
    edgeReq.pageNum = data.currentPage;
    edgeReq.pageSize = data.pageSize;
    onQuery(false);
};

const updateEdgeUrl = () => {
    if (validateUrl()) {
        edgeUrl.value = `http://${edgeIpAndPort.value}/m1/3534901-2178064-default/iea/v1/wirerope/file/getreoports`;
    }
};
</script>

<style lang="scss" scoped>
.icon-gangsishengbaojing {
    font-size: 32px;
}
.greenLight {
    color: #67c23a;
}
.blueLight {
    color: #409eff;
}
.yellowLight {
    color: #f4ea2a;
}
.orangeLight {
    color: #fea821;
}
.grayLight {
    color: #909399;
}
</style>
